import React from 'react';
import { connect } from 'dva';
import { Tree, Button, Table, Form, Input, Select, Popconfirm } from 'antd';
import UserModal from '../../components/sys/UserModal';
const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;

function User({ dispatch, user, loading, form }) {

  const { getFieldDecorator, getFieldsValue, getFieldValue } = form;

  const { currentItem, modalVisible, modalType } = user

  const loop = data => data.map((item) => {
      if (item.depts && item.depts.length) {
        return <TreeNode key={item.id_} title={item.name}>{loop(item.depts)}</TreeNode>;
      }
      return <TreeNode key={item.id_} title={item.name} />;
  });

  const modalProps = {
    item: modalType === 'create' ? {} : user.currentItem,
    depts: user.deptTree,
    roles: user.roleList,
    visible: modalVisible,
    type: modalType,
    maskClosable: false,
    confirmLoading: loading,
    title: `${modalType === 'create' ? '新增用户' : '更新用户'}`,
    wrapClassName: 'vertical-center-modal',
    newKey : user.newKey,
    onOk (data) {
      dispatch({
        type: `user/${modalType}`,
        payload: data,
      })
    },
    onCancel () {
      dispatch({
        type: 'user/hideModal',
      })
    },
  }

  const columns = [{
    title: '用户名',
    dataIndex: 'account',
    key: 'account',
    width: 100,
  }, {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  }, {
    title: '性别',
    dataIndex: 'sex',
    key: 'sex',
    width: 50,
  }, {
    title: '电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 100,
  }, {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    width: 150,
  }, {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 50,
     render: (text, record) => {
      if (record.status == 1) {
        return '正常';
      };
      if (record.status == 2) {
        return '停用';
      };
      if (record.status == 3) {
        return '禁用';
      };
    },
  }, {
    title: '操作',
    key: 'operation',
    width: 100,
    render: (text, record) => (
        <span>
            <a onClick={onEditItem.bind(null, record.id_)}>编辑</a>
            <span className="ant-divider" />
            <Popconfirm title="确认删除？" onConfirm={deleteHandler.bind(null, record.id_)}>
            <a>删除</a>
            </Popconfirm>
        </span>
    ),
  }];

  const pagination = {
    current:user.current,
    pageSize:user.currentSize,
    total: user.total,
    showSizeChanger: true,
    showTotal: (total => '共' + user.total + '条'),
    onShowSizeChange(current, size) {
      dispatch({
        type: 'user/qryUserByParams',
        payload: { ...getFieldsValue(),...{'pageNum':current, 'pageSize':size} },
      });
    },
    onChange(current) {
      dispatch({
        type: 'user/qryUserByParams',
        payload:{ ...getFieldsValue(),...{'pageNum': current, 'pageSize':user.currentSize} }
      });
    },
  };

  const submitHandle = () => {
    dispatch({
        type: 'user/qryUserByParams',
        payload: { ...getFieldsValue()},
    });
  }

  const onAdd = () => {
    dispatch({
      type: 'user/showModal',
      payload: {
        modalType: 'create',
      },
    })
  }

 const onEditItem = (id) => {
    dispatch({
      type: 'user/qryUserById',
      payload: id,
    })
  }

  const onSelect = (info) => {    
    if(info.length > 0){
      dispatch({
        type: 'user/qryUserByParams',
        payload: { ...getFieldsValue(),...{'deptId':info[0]} },
      });
    }else{
      dispatch({
        type: 'user/qryUserByParams',
        payload: { ...getFieldsValue(),...{'deptId':null}},
      });
    }
  }

  function deleteHandler(id) {
    dispatch({
      type: 'user/remove',
      payload: {id:id,search:{...getFieldsValue()}},
    });
  }

  return (
    <div style={{backgroundColor:'#fff',}}>
        <div style={{width:'250px',float: "left"}}>
            <div style={{width:'100%',height:'40px',backgroundColor:'#232f40',lineHeight:'40px',color:'#fff',paddingLeft:'20px',fontSize:'14px',fontWeight:'400'}}>
            组织结构树
            </div>
            <div style={{width:'100%',}}>
            <Tree
                defaultExpandedKeys = {['1']}
                onSelect={onSelect}
            >            
              { user.deptTree && loop(user.deptTree) }
            </Tree>
            </div>
        </div>
        <div style={{marginLeft:'250px'}}>
           <div style={{backgroundColor:'#fff',lineHeight:'40px',paddingLeft:'20px',paddingTop:'10px'}}>
                <Form layout="inline" >
                    <FormItem>
                    {getFieldDecorator('deptId',{initialValue:user.deptId})(
                        <Input type="hidden"/>
                    )}
                    </FormItem>

                    <FormItem>
                    {getFieldDecorator('account',{initialValue:''})(
                        <Input type="text" placeholder="用户名" style={{ width:'100px', marginRight: '3%' }} />
                    )}
                    </FormItem>
                    <FormItem>
                    {getFieldDecorator('name',{initialValue:''})(
                        <Input type="text" placeholder="姓名" style={{ width:'100px', marginRight: '3%' }} />
                    )}
                    </FormItem>
                    <FormItem>
                    {getFieldDecorator('phone',{initialValue:''})(
                        <Input type="text" placeholder="电话" style={{ width:'100px', marginRight: '3%' }} />
                    )}
                    </FormItem>
                    <FormItem>
                    {getFieldDecorator('email',{initialValue:''})(
                        <Input type="text" placeholder="邮箱" style={{ width:'120px', marginRight: '3%' }} />
                    )}
                    </FormItem>
                    <FormItem>
                    {getFieldDecorator('status')(
                        <Select placeholder="状态" style={{ width: '60px' }} allowClear>
                            <Option value="1">正常</Option>
                            <Option value="2">停用</Option>
                            <Option value="3">禁用</Option>
                        </Select>
                    )}
                    </FormItem>
                    <FormItem>
                        <Button type="primary" size='large' onClick={submitHandle} className='ant-search-btn'>查询</Button>
                    </FormItem>
                    <div style={{marginTop:'-40px',textAlign:'right',paddingRight:'10px'}}>
                      <FormItem>
                          <Button type="primary" size='large' onClick={onAdd}>新增用户</Button>
                      </FormItem>
                    </div>
                </Form>
            </div>
            <div style={{width:'100%',paddingLeft:'20px',paddingTop:'30px',paddingRight:'20px'}}>
                <Table columns={columns} rowKey={record => record.id_} loading={loading} dataSource={user.userList} pagination={pagination}
                />
            </div>
        </div>
        <div style={{width:'100%',clear:'both'}}></div>
        <UserModal {...modalProps} />
    </div>
  );
}

function mapStateToProps(state) {
  return { user : state.user,loading:state.loading.models.user};
}

User = Form.create()(User);

export default connect(mapStateToProps)(User);
